package com.yygo.webapp.controller.material;

import com.yygo.Constants;
import com.yygo.model.LoanRequest;
import com.yygo.model.Material;
import com.yygo.model.MaterialAudit;
import com.yygo.model.User;
import com.yygo.service.LoanRequestManager;
import com.yygo.service.MaterialAuditManager;
import com.yygo.service.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.security.Principal;
import java.util.Date;
import java.util.List;

/**
 * Created by tiansha on 2015/10/31.
 */
@Controller
@RequestMapping("/sendMaterialsForm")
public class SendMaterialsFormController extends BaseMaterialController {

    @Autowired
    private MaterialAuditManager materialAuditManager;

    @Autowired
    private UserManager userManager;

    @RequestMapping(method = RequestMethod.GET)
    public String batchSend(@RequestParam(required = true, value = "maId") Long maId, @RequestParam(required = true, value = "shipNumber") String shipNumber,
                              @RequestParam(required = true, value = "selectedMaterials") String[] selectedMaterials, Principal principal) {
        User loginUser = userManager.getUserByUsername(principal.getName());
        MaterialAudit materialAudit = materialAuditManager.get(maId);
        materialAudit.setStarted(true);
        if (!loginUser.hasRole(Constants.DEALER_USER_ROLE)) {
            throw new AccessDeniedException("You have no right to send attachments");
        }

        for (String name : selectedMaterials) {
            Material material = getMaterial(materialAudit, name);
            if (material == null) {
                material = new Material();
                material.setName(name);

                material.setMaterialAudit(materialAudit);
                materialAudit.getMaterialList().add(material);
            }
            material.setSent(true);

            material.setShipNumber(shipNumber);
            material.setSendDate(new Date());
        }

        List<Material> materials = materialAudit.getMaterialList();
        List<Material> completeMaterials = buildCompleteMaterials(materialAudit);
        mergeMaterials(materials, completeMaterials);

        /*
        boolean allSent = true;
        for (Material material : completeMaterials) {
            if (!material.isSent()) {
                allSent = false;
            }
        }
        materialAudit.setAllSent(allSent);
        */
        materialAuditManager.save(materialAudit);

        return "redirect:/sendMaterials?maId=" + materialAudit.getId();
    }


}
